package com.example.cylooq.niceview.utils

import android.content.Context
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream

/**
 * Created by RuiChang on 2017/08/25.
 */
object ObjectSaveUtils {
    fun saveObject(context: Context, name: String, value: Any) {
        //文件输出流
        var fileOutputStream: FileOutputStream? = null
        //对象输出流
        var objectOutputStream: ObjectOutputStream? = null
        try {
            fileOutputStream = context.openFileOutput(name, Context.MODE_PRIVATE)
            objectOutputStream = ObjectOutputStream(fileOutputStream)
            objectOutputStream.writeObject(value)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.close()
            }
            if (objectOutputStream != null)
                objectOutputStream.close()
        }

    }

    fun getValue(context: Context, name: String): Any? {
        var fileInputStream: FileInputStream? = null
        var objectInputStream: ObjectInputStream? = null
        try {
            fileInputStream = context.openFileInput(name)
            if (fileInputStream == null) {
                return null
            }
            objectInputStream = ObjectInputStream(fileInputStream)
            return objectInputStream.readObject()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            if (objectInputStream != null) {
                try {
                    objectInputStream.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
        }
        return null
    }

    fun delectFile(name: String, context: Context) {
        context.deleteFile(name)
    }

}